<script setup lang="ts">
import { getRoleResources, allocateRoleResources, type TCategoryItem } from '@/api/roles'
import AllocCategory from './AllocCategory.vue'
import router from '@/router'
const props = defineProps({
  roleId: {
    type: String,
    required: true
  }
})
const allResource = ref<TCategoryItem[]>()
onMounted(async () => {
  const { data } = await getRoleResources(props.roleId)
  // console.log(data)
  if (data.code === '000000') {
    allResource.value = data.data.sort((c1, c2) => c1.id - c2.id)
  } else {
    ElMessage.error('获取角色资源失败')
    throw new Error('获取角色资源失败' + data.mesg)
  }
})
// 存储子组件被选项目
const collectCheckedIds: Ref<number[]>[] = []
// 处理子组件消息
const handleAddCheckIds = (payload: Ref<number[]>) => {
  collectCheckedIds.push(payload)
}
const onSave = async () => {
  const allCheckedIds = collectCheckedIds.reduce((tmp: number[], item) => {
    return [...tmp, ...item.value]
  }, [])
  const { data } = await allocateRoleResources(props.roleId, allCheckedIds)
  if (data.code === '000000') {
    ElMessage.success('角色资源保存成功')
    router.push({ name: 'rolesIndex' })
  } else {
    ElMessage.error('角色资源保存失败')
    throw new Error('角色资源保存失败' + data.mesg)
  }
}
const onClear = () => {
  collectCheckedIds.forEach((item) => {
    item.value = []
  })
}
</script>
<template>
  <div class="container">
    <AllocCategory :category="cate" v-for="cate in allResource" :key="cate.id" @postCheckedIdsRef="handleAddCheckIds" />
    <div class="resource-btn">
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="onClear">清空</el-button>
    </div>
  </div>
</template>
<style scoped lang="scss">
.container {
  color: #000;
}
</style>
